import json
import logging
import os

import openai
import redis

import msg_handler_impl
from const import cfg, QING_YUN_KE_CONF_KEYWORD
from msg_handler_impl.handler import SingleMsgHandlerBase
from util import mirai_utils, msg_send_utils

logger = logging.getLogger()
os.environ["OPENAI_API_KEY"] = "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"
openai.api_key = os.getenv("OPENAI_API_KEY")


def _get_smart_reply(content: str, conf: dict) -> str or None:
    # conf["parmas"].update(msg=content)
    # url = conf["url"] + urlencode(conf["parmas"])
    # resp = requests.get(url)
    # resp.raise_for_status()
    # return resp.json().get("content")

    redis_cli = None
    messages = []
    if msg_handler_impl.REDIS_POOL:
        redis_cli = redis.Redis(connection_pool=msg_handler_impl.REDIS_POOL)
        messages = json.loads(redis_cli.get("CONVERSATION") or '[]')
        if content == 'clear':
            redis_cli.setex('CONVERSATION', 10 * 60, '')
            return 'ok'

        while len(messages) > 1000:
            messages.pop(0)

    # openAi
    messages.append({"role": "user", "content": content})
    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages,
        max_tokens=500,
    )
    completion.choices[0].message.content = completion.choices[0].message.content.strip()
    messages.append(completion.choices[0].message)
    if msg_handler_impl.REDIS_POOL:
        redis_cli.setex('CONVERSATION', 10 * 60, json.dumps(messages, ensure_ascii=False))
    logger.info("当前会话: %s", messages)
    return completion.choices[0].message.content


class SmartReplyMsgHandler(SingleMsgHandlerBase):
    """
    通过青云客API 获取智能回复结果
    """

    def can_handle(self, msg: dict, *args, **kwargs):
        msg_type = msg.get('type')
        check_type = msg_type in ["FriendMessage", "GroupMessage"]
        check_at = msg["messageChain"][1]["type"] == "At" and str(msg["messageChain"][1]["target"]) == cfg["qq"]
        return (check_type and check_at) or msg_type == "FriendMessage"

    def handle(self, msg: dict, ctx, keyword=QING_YUN_KE_CONF_KEYWORD, *args, **kwargs):
        msg_chain = msg['messageChain']
        # Source类型永远为chain的第一个元素: {'type': 'Source', 'id': 26675, 'time': 1661589588}
        source_msg = msg_chain[0]
        logger.info(source_msg)
        conf = ctx.cfg[QING_YUN_KE_CONF_KEYWORD] \
            if QING_YUN_KE_CONF_KEYWORD in ctx.cfg \
            else None
        for single_msg in msg_chain:
            single_msg_type = single_msg['type']
            if conf is not None and single_msg_type == 'Plain':
                content: str = single_msg['text'].strip()
                reply = _get_smart_reply(content, conf)
                if reply is not None:
                    sender_id = mirai_utils.get_sender_id(msg)
                    msg_chain = [
                        {"type": "At", "target": sender_id},
                        {"type": "Plain", "text": " " + reply},
                    ]
                    if msg["type"] == "FriendMessage":
                        msg_send_utils.send_friend_msg(cfg["session"], sender_id, msg_chain[1:])
                    else:
                        msg_send_utils.send_group_msg(cfg["session"],
                                                      mirai_utils.get_group_id(msg),
                                                      msg_chain)
